package com.cats.template.sys.services.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cats.template.sys.exception.SqlException;
import com.cats.template.sys.mapper.UserMapper;
import com.cats.template.sys.pojo.model.UserModel;
import com.cats.template.sys.pojo.model.UserRolesModel;
import com.cats.template.sys.services.UserRolesService;
import com.cats.template.sys.services.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author duxiaobo
 * @date 2021/9/102:37 下午
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserModel> implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRolesService userRolesService;

    @Override
    public UserModel getUser(String userName) {
        return userMapper.getUserByUserName(userName);
    }

    @Override
    public UserModel getUser(String userName, String password) {
        return userMapper.getUserByUserNameAndPassword(userName, password);
    }

    @Override
    public Boolean configRoles(Long userId, Set<Long> roleIds) {
        Boolean deleteFlag = userRolesService.deleteByUserId(userId);
        if (!deleteFlag) {
            log.error("删除用户权限异常:userId={}", userId);
            throw new SqlException();
        }
        List<UserRolesModel> userRolesModels = roleIds.stream().map(roleId -> new UserRolesModel().setUserId(userId).setRoleId(roleId)).collect(Collectors.toList());
        boolean insertFlag = userRolesService.saveOrUpdateBatch(userRolesModels);
        if (!insertFlag) {
            log.error("配置用户权限异常：userId={},roleIds={}", userId, roleIds);
            throw new SqlException();
        }
        return true;
    }
}
